package thread;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

public class ThreadDemo17 {
    public static void test(){
        //创建固定数量的线程池
        ExecutorService pool = Executors.newFixedThreadPool(10);
        //通过submit向线程池中添加任务
        pool.submit(()->{
            System.out.println("hello");
        });
    }
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool pool = new MyThreadPool(10);
        for(int i = 0; i < 1000; i++){
            int num = i;
            pool.submit(()->{
                System.out.println(Thread.currentThread().getName() + "：正在执行"+ num + "号任务" );
            });
        }
    }
}

// 模拟实现一个固定数目的线程池
class MyThreadPool{
    //创建一个容纳任务的阻塞队列
    private BlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue<>();

    //通过submit向阻塞队列中添加任务
    public void submit(Runnable runnable) throws InterruptedException {
        blockingQueue.put(runnable);
    }

    //构造函数，创建固定数量为n的线程池
    public MyThreadPool(int n){
        for(int i = 0; i < n; i++){
            Thread t = new Thread(()->{
                try {
                    while(true){
                        //每个现场要完成的任务，需从阻塞队列中拿到，拿到后执行任务
                        Runnable runnable = blockingQueue.take();
                        runnable.run();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            t.start();
        }
    }
}
